import { Request, toast, formatDate, alert, fileUrl, rpxTopx } from '../../utils/util.js'
import { ALIYUN_URL } from '../../utils/config.js'
let W, H = 0
let request = new Request()
let app = getApp()
Page({

  data: {
    ALIYUN_URL: ALIYUN_URL,
    chatId : 0,
    chat : {
      user : {}
    },
    height : {},
    currentIndex : 0,
    picture : [],
    formId : '',
    qrcode : '',
    showCard : false,
    showSelectShareType : false,

    showGoodsQr : false
  },

  toggleSelectShareType () {
    var show = this.data.showSelectShareType
    this.setData({ showSelectShareType : !show})
  },

  toggleCard () {
    var showCard = this.data.showCard
    this.setData({ showCard: !showCard})
    if (!showCard) {
      this.toggleSelectShareType()
      wx.nextTick(() => {
        this.card()
      })
    }
  },

  card () {
    if (this.data.qrcode === '') {
      let req = new Request()
      req.setConfig('responseType', 'arraybuffer')
      req.get('qr/chat', res => {
        let qrcode = wx.arrayBufferToBase64(res).replace(/[\r\n]/g, '')
        this.setData({ qrcode: qrcode })
        wx.nextTick(() => {
          this.draw()
        })
      }, { chatId: this.data.chatId }).showLoading()
    }else{
      this.draw()
    }
    
  },

  draw() {
    let qrcode = this.data.qrcode
    let chat = this.data.chat
    let pic = fileUrl(chat.cover)
    let userInfo = chat.user
    let avatar = userInfo.avatar
    let nickname = userInfo.nickname
    let self = this
    const query = wx.createSelectorQuery()
    query.select('#canvas-modal').boundingClientRect()
    query.exec(function (res) {
      W = res[0].width
      H = res[0].height

      let avatarW = rpxTopx(86)
      let avatarH = rpxTopx(86)

      var ctx = wx.createCanvasContext('firstCanvas')
      ctx.setFillStyle('#FFE200')
      ctx.fillRect(0, 0, W, H)
      ctx.draw(true)


      wx.getImageInfo({
        src: avatar,
        success: function (res) {
          ctx.drawImage(res.path, 0, 0, 132, 132, rpxTopx(56), rpxTopx(64), avatarW, avatarH)
          ctx.draw(true)
        }
      })

      wx.getImageInfo({
        src: pic,
        success(res) {
          var w = 0
          var h = 0
          var baseSize = 500
          if(res.width <= baseSize) {
            w = res.width
          }else{
            w = baseSize
          }

          if (res.height <= baseSize) {
            h = res.height
          } else {
            h = baseSize
          }

          ctx.drawImage(res.path, 0, 0, res.width, res.height, rpxTopx(120), rpxTopx(250), rpxTopx(w), rpxTopx(h))
          ctx.draw(true)
        }
      })

      wx.getImageInfo({
        src: '/assets/images/dianzan.png',
        success(res) {
          ctx.drawImage('/assets/images/dianzan.png', 0, 0, res.width, res.height, rpxTopx(20), rpxTopx(670), rpxTopx(res.width), rpxTopx(res.height))
          ctx.draw(true)
        }
      })

      ctx.setFillStyle('#333333')
      ctx.setFontSize(rpxTopx(32))
      ctx.fillText(nickname, rpxTopx(162), rpxTopx(120))
      ctx.draw(true)

      ctx.setFillStyle('#333333')
      ctx.setFontSize(rpxTopx(40))
      ctx.fillText('分享推荐', rpxTopx(450), rpxTopx(120))
      ctx.draw(true)


      ctx.setFillStyle('#FFF')
      ctx.fillRect(0, rpxTopx(830), W, H - rpxTopx(830))
      ctx.draw(true)

      ctx.setFillStyle('#333333')
      ctx.setFontSize(rpxTopx(28))
      ctx.fillText(chat.goods_name, rpxTopx(64), rpxTopx(870))
      ctx.draw(true)

      ctx.setFontSize(rpxTopx(44))
      ctx.fillText('￥' + chat.sale_price, rpxTopx(64), rpxTopx(930))
      ctx.draw(true)

      ctx.setFillStyle('#666666')
      ctx.setFontSize(rpxTopx(24))
      ctx.fillText('好产品，分享赚，天天赚', rpxTopx(64), rpxTopx(980))
      ctx.draw(true)


      let d = new Date()
      const fsm = wx.getFileSystemManager()
      const filePath = `${wx.env.USER_DATA_PATH}/` + d.getTime() + '.png'
      const buffer = wx.base64ToArrayBuffer(qrcode)
      fsm.writeFile({
        filePath,
        data: buffer,
        encoding: 'binary',
        success() {
          wx.getImageInfo({
            src: filePath,
            success: (res) => {
              let qrSize = rpxTopx(140)
              ctx.drawImage(res.path, 0, 0, res.width, res.height, rpxTopx(500), rpxTopx(850), qrSize, qrSize)
              ctx.draw(true)
            }
          })
        }
      })
    })
  },

  saveCard() {
    let self = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: W,
      height: H,
      //destWidth: W,
      //destHeight: H,
      fileType : 'jpg',
      quality : 1,
      canvasId: 'firstCanvas',
      success(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            self.toggleCard()
          },
          fail() {
            toast('保存失败')
          }
        })
      }
    })

  },

  swiperChange (e) {
    this.setData({ currentIndex: e.detail.current})
  },

  imageLoad (e) {
    let index = e.currentTarget.dataset.index
    let height = app.systemInfo.windowWidth * e.detail.height / e.detail.width
    let update = {}
    update[`height[${index}]`] = height + 'px'
    this.setData(update)
  },

  addCart () {
    request.post('cart/add', res => {
      if(res.success){
        toast('加入购物车成功')
      }else{
        toast(res.msg)
      }
    }, { id: this.data.chatId, quantity : 1}).showLoading()
  },

  goOnBargain () {
    wx.redirectTo({
      url: '/pages/bargain/index?id=' + this.data.chat.bargain_id
    })
  },

  selectAddress(address) {
    setTimeout(() => {
      this.bargain(address.id)
    }, 500)
  },

  toBargain (e) {
    this.setData({ formId : e.detail.formId})
    wx.navigateTo({
      url: '/pages/deliveryAddress/index?target=select'
    })
  },

  bargain (addressId) {
    request.post('bargain/start', res => {
      if (res.success) {
        wx.redirectTo({
          url: '/pages/bargain/index?id=' + res.data.id,
          fail : function(e){
            console.log(e)
          },
          success : function(){
            console.log('success')
          }
        })
      } else {
        toast(res.msg)
      }
    }, { id: this.data.chatId, address: addressId, formId: this.data.formId}).showLoading()
  },

  toggleCard1() {
    var showGoodsQr = this.data.showGoodsQr
    this.setData({ showGoodsQr: !showGoodsQr })
    if (!showGoodsQr) {
      this.toggleSelectShareType()
      wx.nextTick(() => {
        this.card1()
      })
    }
  },

  card1() {
    if (true || this.data.qrcode === '') {
      let req = new Request()
      req.setConfig('responseType', 'arraybuffer')
      req.get('qr/chat', res => {
        let qrcode = wx.arrayBufferToBase64(res).replace(/[\r\n]/g, '')
        this.setData({ qrcode: qrcode })
        
      }, { chatId: this.data.chatId }).showLoading()
    } else {
      
    }

  },

  draw1() {
    let sef = this
    wx.showLoading()
    let chatId = this.data.chatId
    let qrcode = this.data.qrcode
    const fsm = wx.getFileSystemManager()
    const filePath = `${wx.env.USER_DATA_PATH}/goodsqr-${chatId}.png`
    const buffer = wx.base64ToArrayBuffer(qrcode)
    fsm.writeFile({
      filePath,
      data: qrcode,
      encoding: 'base64',
      success() {
        wx.hideLoading()
        sef.toggleCard1()
        wx.saveImageToPhotosAlbum({
          filePath: filePath,
          success(res) {

          },
          fail() {
            toast('保存失败')
          }
        })
      },
      fail(e) {
        sef.toggleCard1()
        wx.hideLoading()
      }
    })
  },



  onLoad: function (options) {
    request.setMany(true)
    let chatId = options.chatId
    request.get('chat/chat', res => {
      if(res.success){
        let data = res.data
        if(!(data.user instanceof Object)) {
          data.user = JSON.parse(data.user)
        }
        if (!Array.isArray(data.picture)) {
          data.picture = JSON.parse(data.picture)
        }

        data.price = (data.isAgent && data.chat_type != 5) ? data.agent_price : data.sale_price
        
        this.setData({chat : data})
      }else{
        if(res.code == 404){
          alert(res.msg)
        }else{
          toast(res.msg)
        }
      }
    }, { id: chatId}).showLoading()

    if (options.dst === 'share') {
      let sharer = parseInt(options.sharer || 0)
      let userId = app.globalData.userInfo.user_id
      if (sharer != userId) {
        //不是自己分享出去的
        request.post('chat/grabShareAmount', res => {

        }, { chatId: chatId, sharer: sharer})
      }
    }

    this.setData({ chatId: chatId})

    request.setMany(false)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var sceneStr = '?from=goods&chatId=' + this.data.chatId
    var chatType = this.data.chat.chat_type
    if (chatType == 4) {
      let sharer = app.globalData.userInfo.user_id
      sceneStr += ('&sharer=' + sharer)
      sceneStr += '&dst=share'
    }

    sceneStr += ('&fromUserId=' + app.globalData.userInfo.user_id)

    let path = '/pages/index/index?scene=' + encodeURIComponent(sceneStr)
    return {
      path: path,
      imageUrl: fileUrl(this.data.chat.picture[0]),
      title: this.data.chat.goods_name
    }
  }
})